package com.onlyxiahui.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 
 * Date 2019-01-11 13:54:13<br>
 * Description 压缩相关
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class OnlyZipUtil {

	/**
	 * 
	 * Description 字节zip压缩 <br>
	 * Date 2019-03-30 17:28:33<br>
	 * 
	 * @param bytes
	 * @return byte[]
	 * @since 1.0.0
	 */
	public static byte[] zip(byte[] bytes) {
		byte[] b = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ZipOutputStream zip = new ZipOutputStream(bos);
			ZipEntry entry = new ZipEntry("zip");
			entry.setSize(bytes.length);
			zip.putNextEntry(entry);
			zip.write(bytes);
			zip.closeEntry();
			zip.close();
			b = bos.toByteArray();
			bos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}

	/**
	 * 
	 * Description 字节zip解压 <br>
	 * Date 2019-03-30 17:28:10<br>
	 * 
	 * @param bytes
	 * @return byte[]
	 * @since 1.0.0
	 */
	public static byte[] unZip(byte[] bytes) {
		byte[] b = null;
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
			ZipInputStream zip = new ZipInputStream(bis);
			while (zip.getNextEntry() != null) {
				byte[] buf = new byte[1024];
				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while ((num = zip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				b = baos.toByteArray();
				baos.flush();
				baos.close();
			}
			zip.close();
			bis.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}
}